/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014-7-7         admin
 */

package com.tianci.appstore.ui.search;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.uipackage.widget.SlideFocusView;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.search.SearchInputLayout.ClearFocusListener;
import com.tianci.appstore.ui.search.SearchNomalKeyLayout.OnNomalInputListener;
import com.tianci.appstore.ui.search.SearchT9KeyLayout.OnT9InputListener;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.SkyConstants;

/**
 * @author admin
 * @ClassName SearchMainLayout
 * @date 2014-7-7
 */
public class SearchMainLayout extends FrameLayout
        implements OnT9InputListener, OnNomalInputListener, SearchResultListener {
    public static int INPUT_TYPE_T9 = 1;
    public static int INPUT_TYPE_NOMAL = 2;
    private Context mContext;
    private String inputString = "";
    private LinearLayout inputContent;
    private ImageView searchIconView;
    private TextView inputTextView;
    private FrameLayout bottomBtnLayou;
    private Button t9_btn, all_btn;

    private SearchT9KeyLayout t9KeyLayout; // T9键盘
    private SearchNomalKeyLayout nomalKeyLayout; // 全键盘
    private SearchInputLayout mCurrentKeyLayout;
    private OnSearchKeyChangeListener mKeyChangeListener = null;
    private ClearFocusListener mClearFocusListener = null;
    private SlideFocusView.FocusViewRevision mRevision = null;

    private int inputType = 0;
    // 最多支持连续输入15个首字母
    private int maxInputNum = 10;
    private boolean mCanInput = true;
    private SlideFocusView.FocusChangedEvent mFocusChangedEvent = null;
    private int mItemBackId = R.drawable.search_keyboard_selector;
    private int mInputBackId = R.drawable.search_inputtext_bg;
    public static final int SEARCH_SHADOW_X = -50;
    public static final int SEARCH_SHADOW_Y = -25;
    private int mInputTextMarginTop = 95;
    private int mInputMarginTop = 200;

    public SearchMainLayout(Context context, int inputType) {
        super(context);
        mContext = context;
        this.inputType = inputType;
        LinearLayout.LayoutParams main_p = new LinearLayout.LayoutParams(SkyConstants.Div(808),
                LayoutParams.MATCH_PARENT);
        this.setLayoutParams(main_p);
        this.setBackgroundColor(Color.parseColor("#40000000"));
        //this.setBackgroundResource(R.drawable.search_key_bg);
    }

    public void setClearFocusListener(ClearFocusListener listener) {
        t9KeyLayout.setClearFocusListener(listener);
        nomalKeyLayout.setClearFocusListener(listener);
        this.mClearFocusListener = listener;
    }

    public void initUI() {
        initView();
        setSearchTypeLayout();
        postDelayed(new Runnable() {
            @Override
            public void run() {
                mCurrentKeyLayout.setFirstFocus();
            }
        }, 200);
    }

    public void setFocusViewEvent(SlideFocusView.FocusChangedEvent event) {
        this.mFocusChangedEvent = event;
        this.mItemBackId = R.drawable.game_center_search_btn;
        this.mInputBackId = R.drawable.game_center_input_bg;
        this.mInputTextMarginTop = 130;
        this.mInputMarginTop = 200;
        mRevision = new SlideFocusView.FocusViewRevision(SkyConstants.Div(SEARCH_SHADOW_X), SkyConstants.Div(SEARCH_SHADOW_Y));
    }

    public void setSearchKeyChangeListener(OnSearchKeyChangeListener listener) {
        this.mKeyChangeListener = listener;
    }

    private void initView() {
        inputContent = new LinearLayout(mContext);
        inputContent.setOrientation(LinearLayout.HORIZONTAL);
        inputContent.setBackgroundResource(R.drawable.search_inputtext_bg);

        searchIconView = new ImageView(mContext);
        searchIconView.setImageResource(R.drawable.search_icon);

        inputTextView = new TextView(mContext);
        inputTextView.setTextSize(SkyConstants.Dpi(50));
        inputTextView.setTextColor(Color.WHITE);
        inputTextView.setGravity(Gravity.CENTER_VERTICAL);
        inputTextView.setBackgroundColor(Color.TRANSPARENT);
        inputTextView.setFocusable(false);
        LinearLayout.LayoutParams input_p = new LinearLayout.LayoutParams(SkyConstants.Div(490),
                SkyConstants.Div(79));
        input_p.leftMargin = SkyConstants.Div(70);
        input_p.gravity = Gravity.CENTER_VERTICAL;
        inputContent.addView(inputTextView, input_p);

        LinearLayout.LayoutParams search_icon_p = new LinearLayout.LayoutParams(
                SkyConstants.Div(40), SkyConstants.Div(40));
        search_icon_p.gravity = Gravity.CENTER_VERTICAL;
        inputContent.addView(searchIconView, search_icon_p);

        bottomBtnLayou = new FrameLayout(mContext);
        t9_btn = new Button(mContext);
        setFocusChangeEvent(t9_btn);
        t9_btn.setTag("t9");
        t9_btn.setOnClickListener(btnClickListener);
        t9_btn.setOnKeyListener(btnOkeyListener);
        t9_btn.setText(R.string.search_t9_name);
        t9_btn.setTextColor(0xfffffefe);
        t9_btn.setTextSize(SkyConstants.Dpi(40));
        t9_btn.setBackgroundResource(mItemBackId);
        t9_btn.setPadding(SkyConstants.Div(80), 0, SkyConstants.Div(80), 0);
        all_btn = new Button(mContext);
        setFocusChangeEvent(all_btn);
        all_btn.setTag("all");
        all_btn.setOnClickListener(btnClickListener);
        all_btn.setOnKeyListener(btnOkeyListener);
        all_btn.setText(R.string.search_key_name);
        all_btn.setTextColor(0xfffffefe);
        all_btn.setTextSize(SkyConstants.Dpi(40));
        all_btn.setBackgroundResource(mItemBackId);
        all_btn.setPadding(SkyConstants.Div(80), 0, SkyConstants.Div(80), 0);
        t9KeyLayout = new SearchT9KeyLayout(mContext);
        t9KeyLayout.setFocusChangeEvent(mFocusChangedEvent);
        t9KeyLayout.initView();
        t9KeyLayout.setOnT9InputListener(this);
        nomalKeyLayout = new SearchNomalKeyLayout(mContext);
        nomalKeyLayout.setFocusChangeEvent(mFocusChangedEvent);
        nomalKeyLayout.initView();
        nomalKeyLayout.setOnNomalInputListener(this);

        t9KeyLayout.setButtons(t9_btn, all_btn);
        nomalKeyLayout.setButtons(t9_btn, all_btn);

        FrameLayout.LayoutParams input_content_p = new FrameLayout.LayoutParams(
                SkyConstants.Div(620), SkyConstants.Div(90));
        input_content_p.gravity = Gravity.CENTER_HORIZONTAL;
        input_content_p.topMargin = SkyConstants.Div(mInputTextMarginTop);
        this.addView(inputContent, input_content_p);

        FrameLayout searchContent = new FrameLayout(mContext);

        FrameLayout.LayoutParams search_p = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        search_p.gravity = Gravity.CENTER_HORIZONTAL;
        search_p.topMargin = SkyConstants.Div(mInputMarginTop);
        this.addView(searchContent, search_p);
        searchContent.addView(t9KeyLayout);
        searchContent.addView(nomalKeyLayout);

        FrameLayout.LayoutParams bottom_p = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        bottom_p.topMargin = SkyConstants.Div(860);
        this.addView(bottomBtnLayou, bottom_p);
        LayoutParams params_p = new LayoutParams(
                SkyConstants.Div(325 + SkyConstants.shadowWidth * 2), SkyConstants.Div(180),
                Gravity.LEFT);
        params_p.setMargins(SkyConstants.Div(55), 0, 0, 0);
        bottomBtnLayou.addView(t9_btn, params_p);
        FrameLayout.LayoutParams all_p = new FrameLayout.LayoutParams(
                SkyConstants.Div(325 + SkyConstants.shadowWidth * 2), SkyConstants.Div(180),
                Gravity.RIGHT);
        all_p.leftMargin = SkyConstants.Div(-SkyConstants.shadowWidth + 5);
        all_p.rightMargin = SkyConstants.Div(55);
        bottomBtnLayou.addView(all_btn, all_p);
        setInputTipsValue(R.string.search_input_tips);
        inputType = getInputSharePreference();
        setSearchTypeLayout();

    }

    private void setFocusChangeEvent(View view) {
        if (mFocusChangedEvent != null) {
            mFocusChangedEvent.registerView(view, mRevision);
        }
    }

    OnKeyListener btnOkeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (v.getTag().equals("t9")) {
                    if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                        all_btn.requestFocus();
                        return true;
                    }
                    if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                        if (inputType == INPUT_TYPE_T9) {
                            t9KeyLayout.setDeleteLayoutFocus();
                        } else if (inputType == INPUT_TYPE_NOMAL) {
                            nomalKeyLayout.setDeleteLayoutFocus();
                        }
                        return true;
                    }
                } else if (v.getTag().equals("all")) {
                    // 按键焦点处理
                    if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                        if (inputType == INPUT_TYPE_T9) {
                            t9KeyLayout.setClearLayoutFocus();
                        } else if (inputType == INPUT_TYPE_NOMAL) {
                            nomalKeyLayout.setClearLayoutFocus();
                        }
                        return true;
                    } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                        if (mClearFocusListener != null) {
                            return mClearFocusListener.clearFocus(keyCode);
                        }
                    }
                }
            }
            return false;
        }
    };

    private void setInputTipsValue(int strid) {
        inputTextView.setTextColor(0xffb6b6b6);
        inputTextView.setTextSize(SkyConstants.Dpi(36));
        String firstLetter = getResources().getString(R.string.search_first_letter);
        String tips = String.format(getResources().getString(strid), firstLetter);
        SpannableString s = new SpannableString(tips);
        int start = tips.indexOf(firstLetter);
        CharacterStyle span = new ForegroundColorSpan(0xff88b8d9);
        s.setSpan(span, start, start + firstLetter.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        inputTextView.setText(s);
    }

    private void setSearchTypeLayout() {
        Resources res = mContext.getResources();
        Drawable myImage = res.getDrawable(R.drawable.do_complete);
        myImage.setBounds(1, 1, SkyConstants.Div(80), SkyConstants.Div(80));
        if (inputType == INPUT_TYPE_T9) {
            t9KeyLayout.setVisibility(View.VISIBLE);
            nomalKeyLayout.setVisibility(View.INVISIBLE);

            t9_btn.setCompoundDrawables(myImage, null, null, null);
            all_btn.setCompoundDrawables(null, null, null, null);
            mCurrentKeyLayout = t9KeyLayout;
        } else if (inputType == INPUT_TYPE_NOMAL) {
            t9KeyLayout.setVisibility(View.INVISIBLE);
            nomalKeyLayout.setVisibility(View.VISIBLE);
            all_btn.setCompoundDrawables(myImage, null, null, null);
            t9_btn.setCompoundDrawables(null, null, null, null);
            mCurrentKeyLayout = nomalKeyLayout;
        }
        setInputSharePreference(inputType);
    }

    private void setInputSharePreference(int type) {
        SharedPreferences preferences = mContext.getSharedPreferences("input", 0);
        Editor editor = preferences.edit();
        editor.putInt("input_type", type);
        editor.commit();
    }

    private int getInputSharePreference() {
        SharedPreferences preferences = mContext.getSharedPreferences("input", 0);
        return preferences.getInt("input_type", 1);
    }

    OnClickListener btnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getTag().equals("t9")) {
                inputType = INPUT_TYPE_T9;
                setSearchTypeLayout();
                submitInputChange(t9_btn.getText().toString());
            } else if (v.getTag().equals("all")) {
                inputType = INPUT_TYPE_NOMAL;
                setSearchTypeLayout();
                submitInputChange(all_btn.getText().toString());
            }
        }
    };

    private void submitInputChange(final String name) {
    }

    // 输入
    public void addValue(String addString) {
        if (mCanInput) {
            if (inputString.length() >= maxInputNum) {
                TipToast.getInstance(mContext)
                        .showTipToast(getResources().getString(R.string.can_not_input));
                return;
            }
            inputString = inputString + addString;
            updateValue();
        } else {
            TipToast.getInstance(mContext)
                    .showTipToast(getResources().getString(R.string.can_not_input));
        }
    }

    // 清空
    public void clearValue() {
        mCanInput = true;
        if (inputString.equals("")) {
            TipToast.getInstance(mContext)
                    .showTipToast(getResources().getString(R.string.no_word_to_clear));
        } else {
            inputString = "";
            updateValue();
        }
    }

    // 是否需回调，且长度应该限制
    private void updateValue() {
        LogUtils.d("search", "updateValue inputString == " + inputString);
        inputTextView.setTextSize(SkyConstants.Dpi(50));
        inputTextView.setTextColor(Color.WHITE);
        inputTextView.setText(inputString);
        if (inputString.length() == 0) {
            setInputTipsValue(R.string.search_input_tips);
        }
        sendSearchCmd(inputString);
    }

    // 发送搜索关键字
    private void sendSearchCmd(String searchString) {
        if (mKeyChangeListener != null) {
            mKeyChangeListener.searchKeyChange(searchString);
        }
    }

    // 删除
    public void deleteValue() {
        mCanInput = true;
        if (inputString.length() >= 1) {
            inputString = inputString.substring(0, inputString.length() - 1);
            updateValue();
        } else {
            TipToast.getInstance(mContext)
                    .showTipToast(getResources().getString(R.string.no_word_to_delete));
        }
    }

    @Override
    public void inputEvent_t9(String str) {
        LogUtils.d("search", "inputEvent_t9 == " + str);
        addValue(str);
    }

    @Override
    public void deletEvent_t9() {
        deleteValue();
    }

    @Override
    public void clearEvent_t9() {
        clearValue();
    }

    @Override
    public void inputEvent_nomal(String str) {
        LogUtils.d("search", "inputEvent_nomal == " + str);
        addValue(str);
    }

    @Override
    public void deletEvent_nomal() {
        deleteValue();
    }

    @Override
    public void clearEvent_nomal() {
        clearValue();
    }

    @Override
    public void onSearchResult(String searchKey, int resultSize) {
        //        if (resultSize == 0)
        //        {
        //            mCanInput = false;
        //        }else {
        //            mCanInput = true;
        //        }
    }
}
